const WEB_PATH = 'http://47.105.183.120'

// const WEB_PATH = 'http://localhost:5500'

/**
 * 获取url参数
 * @param key
 * @returns {null|*}
 */
function getUrlParam(key) {
    var reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = window.location.search.substr(1).match(reg);  //匹配目标参数
    if (r != null) return unescape(r[2]);
    return null; //返回参数值
}

$(() => {
    /**
     * 添加菜单
     */
    function addMenu() {
        let menuData = []
        $.getJSON('/data.json', (data) => {
            menuData = data.header_menu
            //首页头部菜单项模板
            const MenuItemTemplate = `
            <div class="header_menu-item">
                <a href=""></a>
            </div>`

            const menu = $(".header_menu");
            for (let i = 0; i < menuData.length; i++) {
                addMenuItem(menu, menuData[i], MenuItemTemplate, i !== menuData.length - 1)
            }
        });
    }

    /**
     * 根据模板添加菜单子项
     * @param father    父节点
     * @param children  子节点信息
     * @param childrenTemplate  子节点模板
     * @param line  是否有分隔线
     */
    function addMenuItem(father, children, childrenTemplate, line = true) {
        let c = $(childrenTemplate)
        let u
        if (children.url.indexOf("http") == 0) u = children.url
        else u = WEB_PATH + children.url + (children.index ? '?i=' + children.index : '')
        c.find('a').attr('href', u).text(children.title)
        if (children.url.indexOf("http") == 0) c.find('a').attr("target", "_blank")
        const MenuLineTemplate = `<div class="header_menu-line">|</div>`;

        if (children.sub) {
            c.append($(`<div class="header_sub_menu"></div>`))
            c.on('mouseenter', () => {
                c.find('.header_sub_menu').show()
            })
            c.on('mouseleave', () => {
                c.find('.header_sub_menu').hide()
            })
            for (let i = 0; i < children.sub.length; i++) {
                addMenuItem(c.find('.header_sub_menu'), children.sub[i], childrenTemplate, false)
            }
        }
        father.append(c)
        line && father.append($(MenuLineTemplate))
    }

    addMenu()
})